//
//  RHForgotViewController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/19.
//

#import "RHForgotViewController.h"
#import "NSAttributedString+YYText.h"
#import "YYLabel.h"
#import "RHAuthCodeViewController.h"
#import "RHCustomTimer.h"
#import "LCMD5Tool.h"
#import "RHGolbalRegionModel.h"
#import "RHTools.h"
#import "RHChioceRegionTypeVC.h"

@interface RHForgotViewController ()<UITextFieldDelegate>

@property (nonatomic ,strong) UIView *contentView;

@property(nonatomic ,strong) QMUIButton *sendBtn;

@property (nonatomic ,strong)NSMutableArray *TFArr;

@property(nonatomic, strong)NSTimer *timer;

@property(nonatomic, assign)int second;

//国家代码列表选择
@property (nonatomic ,strong) NSArray *countryCodeArr;
@end

@implementation RHForgotViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
-(void)setPara:(NSMutableDictionary *)para
{
    _para = [NSMutableDictionary dictionaryWithDictionary:para];
}

#pragma mark -----  获取验证码
-(void)getVerificationCode
{
    //邮箱校验
    NSString *email =  [(QMUITextField*)self.TFArr[1] text];
     if(![NSString isValidateEmail:email]){
         [QMUITips showError:@"邮箱格式错误".rh_localized];
         return;
     }
     
    NSDictionary *para = @{@"sendEmail":email,
                           @"action":@"忘记密码,获取验证码"};
    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:H_sendCodeNoToken header:@{@"brandId":brand_id} argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        self.sendBtn.userInteractionEnabled = NO;
        
        self.second = 60;
        [self seccondReduce];
        self.timer = [RHCustomTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(seccondReduce) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];

    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {

    }];
}

#pragma mark ------ 获取全球路由

-(void)getCountryRegionCode
{
    //根据全球国家编码
    [QMUITips showLoadingInView:self.view];
    [RHGolbalRegionModel startWithBaseUrl:base_global_url_dev APIKey:G_getCountries argument:@{} requestMethod:RequestMethodPOST requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.countryCodeArr = resultModel.data;
            [self showCountryList];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}

-(void)showCountryList
{
    [self.view endEditing:YES];
    NSMutableArray *countryArr = [NSMutableArray array];
    for (int i = 0; i<self.countryCodeArr.count; i++) {
        RHGolbalRegionModel *model = self.countryCodeArr[i];
//        [countryArr addObject:[RHTools getRegionNameWithCode:model.countryCode]];//翻译
        [countryArr addObject:model.countryName];//不翻译
    }
    RHChioceRegionTypeVC *vc = [[RHChioceRegionTypeVC alloc] initWithData:countryArr];
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    kWeakSelf;
    NSLog(@"---->%@",[self.para class]);
    vc.selectBlock = ^(NSInteger index) {
        QMUITextField *tf = (QMUITextField*)weakSelf.TFArr[0];
        RHGolbalRegionModel *model = self.countryCodeArr[index];
//        tf.text = [RHTools getRegionNameWithCode:model.countryCode];//翻译
        tf.text = model.countryName;//不翻译
        //国家区域编码
        [weakSelf.para setObject:model.countryName forKey:@"country"];
        [weakSelf.para setObject:model.countryCode forKey:@"regionCode"];
    };
}

-(void)seccondReduce{
    self.second--;
    if(self.second ==0){
        [self.timer invalidate];
        self.title = nil;
        [self.sendBtn setTitle:@"获取验证码".rh_localized forState:UIControlStateNormal];
        [self.sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.sendBtn setBackgroundColor:CMainColorGreen];
        self.sendBtn.userInteractionEnabled = YES;
    }else{
        [self.sendBtn setTitle:[NSString stringWithFormat:@"%d",self.second] forState:UIControlStateNormal];
        [self.sendBtn setTitleColor:CMainColorGreen forState:UIControlStateNormal];
        [self.sendBtn setBackgroundColor:kCOLOR_HEX(@"E7E7E7")];
        self.sendBtn.userInteractionEnabled = NO;
        
    }
}
- (void)setupUI{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(appBecomActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    self.second = 60;
    [self.view setBackgroundColor:UIColor.whiteColor];
    _TFArr = [NSMutableArray array];
    
    
    UIScrollView *scroll = [[UIScrollView alloc] init];
    [self.view addSubview:scroll];
    scroll.backgroundColor = [UIColor clearColor];
    scroll.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    if (@available(iOS 13.0, *)) {
        scroll.automaticallyAdjustsScrollIndicatorInsets = NO;
    } else {
        // Fallback on earlier versions
    }
    
    kWeakSelf;
    [scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(weakSelf.view);
    }];
    
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = CMainColorGreen;
    [scroll addSubview:_contentView];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(scroll);
        make.width.mas_equalTo(scroll);
        make.height.greaterThanOrEqualTo(@0.f);//此处保证容器View高度的动态变化 大于等于0.f的高度
    }];
    
    //logo 欢迎
    UIView *top_bgView = [[UIView alloc] init];
    [top_bgView setGradientBackgroundWithColors:@[kCOLOR_HEX(@"#6AD68A"),kCOLOR_HEX(@"#5FCCB4")] orientation:GradientOrientationLeftToRight];
    [_contentView addSubview:top_bgView];
    [top_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_offset(0);
    }];
    
    
    QMUILabel *titleLab = [[QMUILabel alloc] init];
    titleLab.numberOfLines = 0;
    [titleLab setText:@"忘记密码?".rh_localized];
    [titleLab setTextColor:UIColor.whiteColor];
    [titleLab setTextAlignment:NSTextAlignmentLeft];
    [titleLab setFont:kSYSTEMFONT(24)];
    [top_bgView addSubview:titleLab];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(kSafe_top+55);
        make.bottom.mas_offset(-90);
    }];
    
    UIView *bg_view = [[UIView alloc] init];
    [bg_view setBackgroundColor:UIColor.clearColor];
    bg_view.layer.cornerRadius = 15;
    bg_view.layer.masksToBounds = YES;
    bg_view.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bg_view.clipsToBounds = YES;
    [_contentView addSubview:bg_view];
    [bg_view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(top_bgView.mas_bottom).offset(-70);

    }];
    
    UIView *gradientView = kView;
    [gradientView setGradientBackgroundWithColors:@[kCOLOR_HEX_A(@"#FFFFFF",0.6),kCOLOR_HEX_A(@"#FFFFFF",0.9),kCOLOR_HEX_A(@"#FFFFFF",1),kCOLOR_HEX_A(@"#FFFFFF",1)] orientation:GradientOrientationTopToBottom locations:@[@(0),@(0.2),@(0.4),@(1)]];
    [bg_view addSubview:gradientView];
    [gradientView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
    }];
    
    //模糊蒙版本
    UIVisualEffectView *effctVeiw = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect qmui_effectWithBlurRadius:3]];
    [bg_view addSubview:effctVeiw];
    [effctVeiw mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    NSArray *titles = @[@"国家/地区".rh_localized,@"邮箱".rh_localized,@"验证码".rh_localized,@"新密码".rh_localized,@"确认密码".rh_localized];
    NSArray *placeholders = @[@"请选择国家/地区".rh_localized,@"请输入邮箱".rh_localized,@"请输入验证码".rh_localized,@"请输入新密码".rh_localized,@"请输入确认密码".rh_localized];
    NSMutableArray *array = [NSMutableArray array];
    [placeholders enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView *view = [[UIView alloc] init];
        [view setBackgroundColor:UIColor.clearColor];
        [bg_view addSubview:view];
        [array addObject:view];
        
        QMUILabel *titleLab = [QMUILabel labelWithFont:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#474B53") textAligment:NSTextAlignmentLeft];
        titleLab.text = titles[idx];
        [view addSubview:titleLab];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(10);
            make.left.mas_offset(5);
            make.right.mas_offset(0);
        }];
        
        UIView *textField_bg = [[UIView alloc] init];
        textField_bg.backgroundColor = UIColor.clearColor;
        [textField_bg.layer setCornerRadius:8.0];
        [view addSubview:textField_bg];
        
            
        [textField_bg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(5);
            make.right.mas_offset(-5);
            make.bottom.mas_offset(0);
            make.top.equalTo(titleLab.mas_bottom).offset(5);
        }];
        
        
        
        QMUITextField *textField = [[QMUITextField alloc] init];
        [textField setPlaceholder:placeholders[idx]];
        textField.font = kSYSTEMFONT(14);
        textField.textInsets = UIEdgeInsetsMake(0, 5, 0, 0);
        textField.backgroundColor = UIColor.clearColor;
        textField.qmui_borderColor = kCOLOR_HEX(@"#CDD0D6");
        textField.qmui_borderWidth = 1;
        textField.qmui_borderPosition = QMUIViewBorderPositionTop|QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight|QMUIViewBorderPositionBottom;
        textField.layer.cornerRadius = 8;
        [textField_bg addSubview:textField];
        textField.tag = idx;
        [_TFArr addObject:textField];
        
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsMake(2, 0, 2, 0));
            make.height.offset(44);
        }];
        
        if(idx == 0){
            textField.userInteractionEnabled = NO;
            UIImageView *arrowImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"nav_arrow_down"]];
            arrowImg.contentMode = UIViewContentModeScaleAspectFit;
            [textField_bg addSubview:arrowImg];
            [arrowImg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.offset(15);
                make.right.mas_offset(-15);
                make.centerY.mas_offset(0);
            }];
            
            QMUIButton *countryBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
            [textField_bg addSubview:countryBtn];
            [countryBtn addTarget:self action:@selector(getCountryRegionCode) forControlEvents:UIControlEventTouchUpInside];
            [countryBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.insets(UIEdgeInsetsZero);
            }];
//            textField.text = [RHTools getRegionNameWithCode:weakSelf.para[@"regionCode"]];//翻译
            textField.text = weakSelf.para[@"country"];//不翻译
        }
        
        if(idx == 1){//邮箱
            textField.maximumTextLength = 64;
            textField.keyboardType = UIKeyboardTypeEmailAddress;
        }
        if(idx == 2){//验证码
            textField.maximumTextLength = 6;
            textField.keyboardType = UIKeyboardTypePhonePad;
            
            _sendBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
            _sendBtn.backgroundColor = CMainColorGreen;
            _sendBtn.layer.cornerRadius = 8;
            [_sendBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
            [_sendBtn setTitle:@"获取验证码".rh_localized forState:UIControlStateNormal];
            _sendBtn.titleLabel.font = [UIFont systemFontOfSize:13];
            [_sendBtn setCornerRadius:8];
            [_sendBtn.titleLabel sizeToFit];
            [view addSubview:_sendBtn];
            CGFloat width = [_sendBtn.titleLabel.text getStringWidthFont:_sendBtn.titleLabel.font limitHeight:20];
            [_sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(textField_bg);
                make.right.mas_offset(-5);
                make.bottom.mas_offset(0);
                make.width.offset(width+15);
            }];

             [[_sendBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                 [weakSelf getVerificationCode];
             }];
            
            [textField mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(0);
                make.top.mas_offset(2);
                make.bottom.mas_offset(-2);
                make.right.equalTo(weakSelf.sendBtn.mas_left).mas_offset(-10);
                make.height.offset(44);
            }];
        }
        if(idx == 3||idx == 4){//密码
            textField.maximumTextLength = 16;
            textField.keyboardType = UIKeyboardTypeASCIICapable;
            textField.secureTextEntry = YES;
            //隐藏/显示密码
            QMUIButton *showPwdBtn = [[QMUIButton alloc]init];
            [showPwdBtn setImage:[UIImage imageNamed:@"kwt_show_pwd"] forState:UIControlStateNormal];
            [showPwdBtn setImage:[UIImage imageNamed:@"kwt_show_pwd_s"] forState:UIControlStateSelected];
            [textField_bg addSubview:showPwdBtn];
            [showPwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.offset(35);
                make.right.equalTo(textField).offset(-5);
                make.centerY.equalTo(textField);
            }];
            
            [[showPwdBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIButton * _Nullable x) {
                x.selected = !x.selected;
                textField.secureTextEntry = !x.selected;
            }];
        }
        
        
        
        
        
    }];
    
    [array mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(10);
        make.right.mas_offset(-10);
    }];
    
    [array mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedSpacing:10 leadSpacing:10 tailSpacing:20];
    
    
    
    UIView *foot_view = [[UIView alloc] init];
    [foot_view setBackgroundColor:UIColor.whiteColor];
    [_contentView addSubview:foot_view];
    
    
    QMUIButton *resetBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [resetBtn setTitle:@"重置密码".rh_localized forState:UIControlStateNormal];
    [resetBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [resetBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [resetBtn setBackgroundColor:CMainColorGreen];
    [resetBtn.layer setCornerRadius:5];
    [resetBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [foot_view addSubview:resetBtn];
    

    [resetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.top.mas_offset(50);
    }];
    
    
    [foot_view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.right.mas_offset(0);
        make.top.equalTo(bg_view.mas_bottom);
        make.bottom.mas_offset(0);
        make.height.mas_equalTo(200);
    }];

    QMUIButton *backBtn = [[QMUIButton alloc]init];
    [backBtn setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(35);
        make.left.mas_offset(8);
        make.top.mas_offset(kSafe_top);
    }];
    [[backBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
   
    

    [[resetBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf resetPassword];
    }];
}

#pragma mark -----   重置密码
-(void)resetPassword
{
    //邮箱校验
    NSString *country =  [(QMUITextField*)self.TFArr[0] text];
     if(country.length == 0){
         [QMUITips showError:@"请选择一个国家/地区".rh_localized];
         return;
     }
    
    //邮箱校验
    NSString *email =  [(QMUITextField*)self.TFArr[1] text];
     if(![NSString isValidateEmail:email]){
         [QMUITips showError:@"邮箱格式错误".rh_localized];
         return;
     }
    
    //验证码校验
    NSString *code =  [(QMUITextField*)self.TFArr[2] text];
     if(![NSString validateVerificationCode:code]){
         [QMUITips showError:@"请输入6位验证码".rh_localized];
         return;
     }
    
    //密码校验
    NSString *password =  [(QMUITextField*)self.TFArr[3] text];
     if(![NSString validatePassword:password]){
         [QMUITips showError:@"密码长度为8 ~ 16，必须包含大写字母、小写字母和数字".rh_localized];
         return;
     }
    
    if (![[(QMUITextField*)self.TFArr[3] text] isEqualToString:[(QMUITextField*)self.TFArr[4] text]]) {
        [QMUITips showError:@"两次输入的密码不一致".rh_localized];
        return;
    };
    
    NSDictionary *para = @{@"email":email,
                           @"recode":code,
                           @"regionCode":ValidNullData(self.para[@"regionCode"]),
                           @"newPassword":[LCMD5Tool md5HexDigest:password],
                           @"country":ValidNullData(self.para[@"country"])
                         };
    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:H_forgetPassword argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"重置密码成功".rh_localized];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [QMUITips showError:resultModel.message];
    }];
}

#pragma mark ------- 自动填充粘贴板的内容
-(void)appBecomActive
{
    NSString *codeStr = [UIPasteboard generalPasteboard].string;
    NSString *reg = @"[0-9]{6}";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",reg];
    BOOL isSixNumber = [predicate evaluateWithObject:codeStr];
    if(isSixNumber){
        [(QMUITextField*)self.TFArr[2] setText:codeStr];
    }
    NSLog(@"---->粘贴板的内容:%@",codeStr);
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
